<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div style="height: 1000px; background-color: pink"></div>
    <img
      id="img-001"
      data-src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"
      data-xxx="xxx"
      data-yyy="yyy"
    />

    <script>
      const imgDOM = document.getElementById('img-001');

      // 1 创建 IntersectionObserver 实例
      const imgObserver = new IntersectionObserver(function (entries) {
        // console.log('img是否进入视口交叉', entries[0].isIntersecting);
        if (entries[0].isIntersecting) {
          console.log('图片可见');
          console.log(imgDOM.dataset.src);
          imgDOM.src = imgDOM.dataset.src;
          // 图片可见后，取消对图片可视交叉的观察
          imgObserver.unobserve(imgDOM);
        } else {
          console.log('图片不可见');
        }
      });

      // 观测
      imgObserver.observe(imgDOM);
    </script>
  </body>
</html>
